package net.projecteuler.prob;

public class Problem32 implements Runnable {

	@Override
	public void run() {
		/** product formular should be the form like
		 *  a * bcde = fghi --- 1.
		 *  ab * cde = fghi --- 2.
		 *  */
		
		// 1. a * bcde = fghi
		for(int a = 2; a < 10; a++){
			for(int bcde = 1000; bcde < 10000; bcde ++){
				int fghi = a * bcde;
				if(pandigital(a, bcde, fghi))
					System.out.println(a + "," + bcde + "," + fghi);
			}
		}
		
		// 2. ab * cde = fghi
		for(int ab = 10; ab < 100; ab++){
			for(int cde = 100; cde < 1000; cde ++){
				int fghi = ab * cde;
				if(pandigital(ab, cde, fghi))
					System.out.println(ab + "," + cde + "," + fghi);
			}
		}
	}

	public boolean pandigital(int a, int b, int c){
		boolean[] check = new boolean[10];
		
		int[] aDigit = digits(a);
		int[] bDigit = digits(b);
		int[] cDigit = digits(c);
		
		if(aDigit.length + bDigit.length + cDigit.length != 9)
			return false;
		
		for(int i = 0; i < aDigit.length; i++){
			int digit = aDigit[i];
			if(digit == 0)
				return false;
			if(check[digit] == true)
				return false;
			check[digit] = true;
		}
		
		for(int i = 0; i < bDigit.length; i++){
			int digit = bDigit[i];
			if(digit == 0)
				return false;
			if(check[digit] == true)
				return false;
			check[digit] = true;
		}
		
		for(int i = 0; i < cDigit.length; i++){
			int digit = cDigit[i];
			if(digit == 0)
				return false;
			if(check[digit] == true)
				return false;
			check[digit] = true;
		}		
		
		return true;
	}
	
	public int[] digits(int value){
		if(value < 0) return null;
		if(value == 0) return new int[]{0};
		
		int digitCnt = 0;
		for(int temp = value; temp > 0; temp /= 10)
			digitCnt++;
		
		int[] result = new int[digitCnt];
		
		for(int i = 0; i < digitCnt; i++){
			result[i] = value % 10;
			value /= 10;
		}
		
		return result;
	}
}
